import React, { useState } from 'react';
import { Form, List, Button, Row, Col, Input, message, Modal, DatePicker } from 'antd';
import '../monitor.less';
import Draggable from 'react-draggable';
import { queryESIndexFilter } from '../service';

const { RangePicker } = DatePicker;

const FilterSearch = (props) => {
  const [index] = useState(props.values.index);
  const [loading, setLoading] = useState(false);
  const [initLoading] = useState(false);
  const [diXianShow, setDiXianShow] = useState('none');
  const [buttonShow, setButtonShow] = useState('none');
  const [list, setList] = useState([]);
  const [disabled, setDisabled] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [messageValue, setMessageValue] = useState('');
  const [searchTimes, setSearchTimes] = useState([]);
  const { onCancel: handleFilterModalVisible, filterModalVisible } = props;

  /**
   * 查询es日志
   * @returns {Promise<boolean>}
   */
  const fetchData = async (queryPage, oldList, Time, messageValue1) => {
    const tableName = `${index.replaceAll('-', '').replaceAll('_', '').replaceAll('.', '')}inner`;
    if (Time && (Time.length !== 0 || messageValue1)) {
      message.loading('正在查询', 0);
      const params = {
        pageSize: 5,
        current: queryPage,
        message: '',
        startTime: '',
        endTime: '',
        tableName,
        type: 'pro',
      };
      if (Time && Time.length !== 0) {
        // eslint-disable-next-line no-underscore-dangle
        const startUTCTime = (new Date(Time[0]._d).getTime() - 28800000).toString();
        // eslint-disable-next-line no-underscore-dangle
        const endUTCTime = (new Date(Time[1]._d).getTime() - 28800000).toString();
        params.startTime = startUTCTime.substring(0, 10);
        params.endTime = endUTCTime.substring(0, 10);
      }

      if (messageValue1) {
        params.message = messageValue1;
      }
      await queryESIndexFilter(params)
        .then((res) => {
          if (res.status === 200) {
            message.destroy();
            message.success('查询成功');
            if (!res.hasMore) {
              message.warn('我已经是底线了');
              setButtonShow('none');
              setDiXianShow('');
            } else {
              setButtonShow('');
              setDiXianShow('none');
            }
            let totalData = oldList.concat(res.data);
            if (params.message !== '' && totalData.length > 0) {
              totalData = totalData.map((item) => {
                const keyword = params.message;
                const re = new RegExp(keyword, 'g');
                const span = `<span class="keyword">${keyword}</span>`;
                return item.replace(re, span);
              });
            }
            totalData = totalData.map((item) => {
              if (item === null) {
                return '';
              }
              return item;
            });
            setList(totalData);
            setLoading(false);
          } else {
            message.destroy();
            message.error('查询失败');
          }
        })
        .catch(() => {
          message.destroy();
          message.error('查询失败');
        });
    } else {
      message.info('请输入时间或者内容进行查询');
    }
  };

  /**
   * 加载更多
   */
  const onLoadMore = () => {
    setLoading(true);
    setCurrentPage(currentPage + 1);
    fetchData(currentPage + 1, list, searchTimes, messageValue);
  };

  /**
   * 搜索框
   * @returns {JSX.Element}
   * @constructor
   */
  const AdvancedSearchForm = () => {
    const [form] = Form.useForm();
    const { getFieldValue } = form;
    const getFields = () => {
      const children = [];
      children.push(
        <Col span={10} key="searchTime">
          <Form.Item
            name="searchTime"
            label="时间"
            rules={[
              {
                required: false,
                message: '时间',
              },
            ]}
            type="array"
          >
            <RangePicker
              showTime
              defaultValue={searchTimes}
              value={searchTimes}
              id="RangePicker"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
        </Col>,
      );
      children.push(
        <Col span={10} key="message">
          <Form.Item
            name="message"
            label="内容"
            rules={[
              {
                required: false,
                message: '请输入内容',
              },
            ]}
          >
            <Input
              placeholder="请输入查询内容"
              defaultValue={messageValue}
              value={messageValue}
              id="Input"
            />
          </Form.Item>
        </Col>,
      );
      children.push(
        <Col span={4} key="caoZuo" style={{ textAlign: 'right' }}>
          <Button
            type="primary"
            onClick={() => {
              let searchTimeValue2 = getFieldValue('searchTime');
              let messageValue2 = getFieldValue('message');
              if (searchTimeValue2 === undefined) {
                searchTimeValue2 = searchTimes;
              } else if (searchTimeValue2 === null) {
                searchTimeValue2 = [];
              }
              if (messageValue2 === undefined) {
                messageValue2 = messageValue;
              }
              fetchData(1, [], searchTimeValue2, messageValue2);
              if (searchTimeValue2 && searchTimeValue2.length === 2) {
                setSearchTimes(searchTimeValue2);
              } else {
                setSearchTimes([]);
              }
              if (messageValue2) {
                setMessageValue(messageValue2);
              } else {
                setMessageValue('');
              }

              // 重新初始化页面参数
              setList([]);
              setCurrentPage(1);
              setDiXianShow('none');
              setButtonShow('none');
            }}
          >
            查询
          </Button>
        </Col>,
      );
      return children;
    };
    return (
      <Form form={form} name="advanced_search" className="ant-advanced-search-form">
        <Row gutter={24}>{getFields()}</Row>
      </Form>
    );
  };

  /**
   * 弹框底部按钮
   * @returns {JSX.Element}
   */
  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => handleFilterModalVisible(false)}>取消</Button>
      </>
    );
  };

  const loadMore =
    !initLoading && !loading ? (
      <div
        style={{
          textAlign: 'center',
          marginTop: 12,
          height: 32,
          lineHeight: '32px',
        }}
      >
        <Button style={{ display: buttonShow }} onClick={onLoadMore}>
          加载更多
        </Button>
      </div>
    ) : null;
  /**
   * 主体渲染
   */
  return (
    <Modal
      width={1000}
      bodyStyle={{
        padding: '10px 10px 10px',
      }}
      closable={false}
      destroyOnClose
      title={
        <div
          style={{
            width: '100%',
            cursor: 'move',
          }}
          onMouseOver={() => {
            if (disabled) {
              setDisabled(false);
            }
          }}
          onMouseOut={() => {
            setDisabled(true);
          }}
          onFocus={() => {}}
          onBlur={() => {}}
        >
          过滤索引日志
        </div>
      }
      modalRender={(modal) => <Draggable disabled={disabled}>{modal}</Draggable>}
      visible={filterModalVisible}
      footer={renderFooter()}
    >
      <div>
        <AdvancedSearchForm />
        <div style={{ overflowY: 'scroll', maxHeight: '600px' }}>
          <List
            className="demo-loadmore-list"
            loading={initLoading}
            itemLayout="horizontal"
            loadMore={loadMore}
            dataSource={list}
            renderItem={(item, itemIndex) => (
              <List.Item key={itemIndex}>
                {/* eslint-disable-next-line react/no-danger */}
                <div dangerouslySetInnerHTML={{ __html: item }} />
              </List.Item>
            )}
          />
        </div>
        <div style={{ textAlign: 'center', display: diXianShow }}>
          <span>一共匹配到{list.length}条数据</span>
        </div>
      </div>
    </Modal>
  );
};

export default FilterSearch;
